package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        Map<String,String> param=new HashMap<>();
        param.put("appid","wx94aba4537af0164b");
        param.put("secret","b15b5729cb57ca0c544b6dc17bb81572");
        param.put("js_code",userLoginDTO.getCode());
        param.put("grant_type","authorization_code");

        String body = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", param);
        String openid = (String) JSONObject.parseObject(body).get("openid");

        if (openid == null) {
            throw new RuntimeException("登录失败");
        }

        User user = this.query()
                .eq("openid", openid)
                .one();
        if (user == null) {
            //说明表中没有openid，是新用户，添加操作，其实就是注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //添加操作
            this.save(user);
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(claims);

        return UserLoginVO.builder()
                .openid(openid)
                .id(user.getId())
                .token(token)
                .build();
    }
}
